import React, { useEffect, useState } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { promptApi } from '@/services/api';
import { toast } from '@/components/ui/use-toast';
import { AlertCircle, RotateCcw } from 'lucide-react';

interface PromptConfig {
  BASE_PROMPT: string;
  LINK: string;
  AI_SUM: string;
  SCREENSHOT: string;
}

const Prompt = () => {
  const [prompts, setPrompts] = useState<PromptConfig>({
    BASE_PROMPT: '',
    LINK: '',
    AI_SUM: '',
    SCREENSHOT: '',
  });
  const [activeTab, setActiveTab] = useState('BASE_PROMPT');
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [resetting, setResetting] = useState(false);

  // 获取所有提示词配置
  const fetchPrompts = async () => {
    try {
      setLoading(true);
      const response = await promptApi.getAllPrompts();
      if (response.code === 0 && response.data) {
        console.log(response.data);
        setPrompts(response.data);
      }
    } catch (error) {
      console.error('获取提示词配置失败:', error);
      toast({
        title: '错误',
        description: '获取提示词配置失败',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 保存提示词配置
  const savePrompt = async () => {
    try {
      setSaving(true);
      const response = await promptApi.updatePrompt(activeTab, prompts[activeTab as keyof PromptConfig]);

      if (response.code === 0) {
        toast({
          title: '成功',
          description: '提示词配置已更新',
        });
      } else {
        throw new Error(response.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存提示词配置失败:', error);
      toast({
        title: '错误',
        description: '保存提示词配置失败',
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  // 从备份文件恢复默认提示词
  const restoreDefaultPrompts = async () => {
    try {
      setResetting(true);
      const response = await promptApi.restoreDefaultPrompts();

      if (response.code === 0) {
        // 重新获取所有提示词配置
        await fetchPrompts();
        toast({
          title: '成功',
          description: '已从备份文件恢复默认提示词',
        });
      } else {
        throw new Error(response.msg || '恢复失败');
      }
    } catch (error) {
      console.error('恢复默认提示词失败:', error);
      toast({
        title: '错误',
        description: '恢复默认提示词失败',
        variant: 'destructive',
      });
    } finally {
      setResetting(false);
    }
  };

  // 处理提示词内容变更
  const handlePromptChange = (content: string) => {
    setPrompts({
      ...prompts,
      [activeTab]: content,
    });
  };

  // 组件加载时获取提示词配置
  useEffect(() => {
    fetchPrompts();
  }, []);

  return (
    <div className="flex flex-col h-screen w-full relative">
      {/* 固定在顶部的标题和选项卡 */}
      <div className="sticky top-0 z-10 bg-white p-6 pb-4 shadow-sm">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">提示词配置</h1>
          <div className="flex items-center">
            <div className="text-amber-500 flex items-center mr-4">
              <AlertCircle className="w-4 h-4 mr-1" />
              <span className="text-sm">修改提示词可能会影响系统功能</span>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={restoreDefaultPrompts}
              disabled={resetting || loading}
              className="flex items-center"
            >
              <RotateCcw className="w-4 h-4 mr-1" />
              {resetting ? '恢复中...' : '恢复默认提示词'}
            </Button>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList>
            <TabsTrigger value="BASE_PROMPT">基础提示词</TabsTrigger>
            <TabsTrigger value="LINK">链接提示词</TabsTrigger>
            <TabsTrigger value="AI_SUM">AI总结提示词</TabsTrigger>
            <TabsTrigger value="SCREENSHOT">截图提示词</TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {/* 可滚动的内容区域 */}
      <div className="flex-1 overflow-auto p-6 pb-24 bg-white">
        {activeTab === 'BASE_PROMPT' && (
          <div className="flex flex-col gap-2">
            <p className="text-sm text-gray-500">基础提示词用于生成笔记的主要内容和结构</p>
            <Textarea
              value={prompts.BASE_PROMPT}
              onChange={(e) => handlePromptChange(e.target.value)}
              className="min-h-[500px] font-mono text-sm"
              placeholder="加载中..."
              disabled={loading}
            />
          </div>
        )}

        {activeTab === 'LINK' && (
          <div className="flex flex-col gap-2">
            <p className="text-sm text-gray-500">链接提示词用于添加时间标记和内容跳转</p>
            <Textarea
              value={prompts.LINK}
              onChange={(e) => handlePromptChange(e.target.value)}
              className="min-h-[300px] font-mono text-sm"
              placeholder="加载中..."
              disabled={loading}
            />
          </div>
        )}

        {activeTab === 'AI_SUM' && (
          <div className="flex flex-col gap-2">
            <p className="text-sm text-gray-500">AI总结提示词用于生成视频内容的总结</p>
            <Textarea
              value={prompts.AI_SUM}
              onChange={(e) => handlePromptChange(e.target.value)}
              className="min-h-[300px] font-mono text-sm"
              placeholder="加载中..."
              disabled={loading}
            />
          </div>
        )}

        {activeTab === 'SCREENSHOT' && (
          <div className="flex flex-col gap-2">
            <p className="text-sm text-gray-500">截图提示词用于指导AI添加截图标记</p>
            <Textarea
              value={prompts.SCREENSHOT}
              onChange={(e) => handlePromptChange(e.target.value)}
              className="min-h-[300px] font-mono text-sm"
              placeholder="加载中..."
              disabled={loading}
            />
          </div>
        )}
      </div>

      {/* 固定在底部的保存按钮 */}
      <div className="fixed bottom-0 left-[300px] right-0 bg-white p-4 shadow-md z-20 border-t">
        <div className="flex justify-end max-w-[1200px] mx-auto">
          <Button
            onClick={savePrompt}
            disabled={saving || loading}
            className="px-6"
          >
            {saving ? '保存中...' : '保存'}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Prompt;
